package models

import (
	"github.com/jinzhu/gorm"
	"kop/libs/database"
	"kop/modules/island/entity"
)

func GetRanking(guildID int32) *entity.IslandGuildRanking {

	var data = entity.IslandGuildRanking{GuildID: guildID}
	if err := database.DB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		}
		panic(err)
	}

	return &data
}

func AddScore(guildID int32, score int64) error {

	return database.DB.Model(&entity.IslandGuildRanking{}).Where("guild_id = ?", guildID).
		UpdateColumn("score", gorm.Expr("score + ?", score)).Error
}

func GetServerRanking(serverID int32, limit int) []*entity.IslandGuildRanking {

	var data []*entity.IslandGuildRanking
	database.DB.Where("server_id = ?", serverID).Order("score DESC").Order("updated_at ASC").Limit(limit).Find(&data)
	return data
}

//func SaveRanking(data *entity.IslandGuildRanking) {
//
//	if err := database.DB.Save(data).Error; err != nil {
//		panic(err)
//	}
//}
